package cn.nfwx.tv.fragment.nyqf;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chan.net.HttpCallback;
import com.chan.net.Result;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.yczbj.ycvideoplayerlib.manager.VideoPlayerManager;
import org.yczbj.ycvideoplayerlib.player.VideoPlayer;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.nfwx.tv.R;
import cn.nfwx.tv.activity.CcpActivity;
import cn.nfwx.tv.adapter.NyqfLiveAdapter;
import cn.nfwx.tv.adapter.NyqfProgramAdapter;
import cn.nfwx.tv.base.BaseFragment;
import cn.nfwx.tv.manager.NyqfManager;
import cn.nfwx.tv.model.TvProgram;
import cn.nfwx.tv.okhttp.UrlHelper;
import cn.nfwx.tv.util.RecyclerViewUtil;

public class ProgramFragment extends BaseFragment {
    @BindView(R.id.rcv_main)
    RecyclerView rcvMain;

    @BindView(R.id.fl_content)
    FrameLayout flContent;

    private Unbinder unbinder;

    NyqfProgramAdapter mAdapter;
    private int mPosition;

    public static ProgramFragment newInstance() {
        return new ProgramFragment();
    }

    @Override
    public View initView() {
        return View.inflate(mContext, R.layout.fragment_cpp, null);
    }

    @Override
    protected boolean isLoadView() {
        return true;
    }

    @Override
    protected void bindView() {
        RecyclerViewUtil.setLinearLayoutManagerWithDivder(mContext, rcvMain);
        mAdapter = new NyqfProgramAdapter();
        rcvMain.setAdapter(mAdapter);
        RecyclerView.ItemDecoration itemDecoration =
                new HorizontalDividerItemDecoration.Builder(mContext)
                        .size(2)
                        .color(Color.parseColor("#99b2b2b2"))
                        .marginResId(R.dimen.dp15, R.dimen.dp15)
                        .build();
        rcvMain.addItemDecoration(itemDecoration);
    }

    @Override
    protected void initLister() {
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                TvProgram tvProgram = (TvProgram) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.fl_item_nyqf_video:
                        if (getActivity() == null) {
                            return;
                        }
                        VideoPlayer videoView = ((CcpActivity) getActivity()).getVideoView();
                        FrameLayout frameLayout = (FrameLayout) view;
                        refreshViewIn(frameLayout);
                        mPosition = position;
                        videoView.continueFromLastPosition(false);
                        videoView.setUp(UrlHelper.getIjkLivePath(tvProgram.getUrl()), null);
                        videoView.start(0);
                        rcvMain.clearOnScrollListeners();
                        rcvMain.addOnScrollListener(onScrollListener);
                        break;
                }
            }
        });

    }

    @Override
    public void initData() {
        loadView.startLoading(flContent);
        NyqfManager.getHotPrograms(0, 10, this.<Result<List<TvProgram>>>bindToLifecycle(), new HttpCallback<List<TvProgram>>() {
            @Override
            public void onSuccess(String requestCommand, Result<List<TvProgram>> data) {
                loadView.removeParentView(flContent);
                mAdapter.setNewData(data.getData());
            }

            @Override
            public void onFail(String requestCommand, Result result) {
                loadView.removeParentView(flContent);
            }
        });
    }

    private void refreshViewIn(FrameLayout frameLayout) {
        if (getActivity() == null) {
            return;
        }
        ((CcpActivity) getActivity()).removePlayerView();
        VideoPlayer videoView = ((CcpActivity) getActivity()).getVideoView();
        mPosition = -1;
        if (frameLayout != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER);
            frameLayout.addView(videoView, frameLayout.getChildCount(), params);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onStop() {
        super.onStop();
        VideoPlayerManager.instance().releaseVideoPlayer();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    protected RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            if (getActivity() != null && ((CcpActivity) getActivity()).hasVideoViewParent()) {
                LinearLayoutManager wrap = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (wrap != null) {
                    int lastPosition = wrap.findLastVisibleItemPosition();
                    int firstPosition = wrap.findFirstVisibleItemPosition();
                    if (mPosition < firstPosition || mPosition > lastPosition) {
                        ((CcpActivity) getActivity()).removePlayerView();
                        rcvMain.removeOnScrollListener(this);
                    }
                }
            }
        }
    };
}
